package com.whynot.frame.auth.shiro.realm;

import com.whynot.frame.auth.jwt.token.JWTToken;
import com.whynot.frame.auth.jwt.utils.JWTUtil;
import com.whynot.frame.auth.shiro.service.UserRealmService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * 描述: shiro认证的Realm:
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: curtain-whynot-shiro-jwt-server
 * 版本: 1.0.0
 * JDK: since 1.8
 */
public class
MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);

    @Autowired
    private UserRealmService userService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //String username = JWTUtil.getUsername(principals.toString());
        //Map<String,Object> user = userService.getUser(map.get("id").toString());
        Map<String,Object> user = (Map<String, Object>) principals.getPrimaryPrincipal();
        String userId = user.get("id").toString();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(userService.findRolesByUser(userId));//设置权限
        simpleAuthorizationInfo.setStringPermissions(userService.findPermissionsByUser(userId));
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。登录调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        Map<String,Object> map = userService.getUser(username);
        if (map == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (! JWTUtil.verify(token, username, map.get("pwd").toString())) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(map, token, "my_realm");
    }
}
